<?php

namespace app\admin\controller\shopro\user;

use Exception;
use fast\Random;
use think\Db;
use app\admin\controller\shopro\Common;
use app\admin\model\shopro\user\Real as RealModel;
use think\exception\PDOException;
use think\exception\ValidateException;

class Real extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new RealModel();
    }

    /**
     * 审核列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->with(["user"=>function($query){
            $query->withField('id,nickname,avatar,mobile');
        }])->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    /**
     * 用户详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $user = $this->model->with(["user"=>function($query){
            $query->withField('id,nickname,avatar,mobile');
        }])->where('id', $id)->find();
        if (!$user) {
            $this->error(__('No Results were found'));
        }

        $this->success('获取成功', null, $user);
    }

    /**
     * 编辑
     * */
    /**
     * 更新用户
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id = null)
    {
        $params = $this->request->only(['name', 'ID_number', 'ID_front', 'ID_opposite', 'status', 'remark']);
        $data = [
            ['name', 'require', '姓名不能为空'],
            ['ID_number', 'require', '身份证号不能为空'],
            ['ID_front', 'require', '请上传身份证'],
            ['ID_opposite', 'require', '请上传身份证'],
            ['status', 'require', '请选择状态'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params['id'] = $id;
        //$this->svalidate($params, '.edit');
        unset($params['id']);
        Db::startTrans();
        try {
            $real = $this->model->where('id', $id)->find();
            $real->save($params);
            if($params["status"]==1){
                $user=\app\admin\model\User::find($real["user_id"]);
                $user->save([
                    "name"=>$params["name"],
                    "ID_number"=>$params["ID_number"],
                    "ID_front"=>$params["ID_front"],
                    "ID_opposite"=>$params["ID_opposite"],
                ]);
            }
            $result=true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success('更新成功', null, $real);
    }

}
